﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Data;
using System.Windows.Media.Imaging;

namespace 餐饮管理系统
{
    public class DatabaseConnect
    {
        SqlConnection conn;

        public void Open()
        {
            //在各自的“xxx\餐饮管理系统\餐饮管理系统\餐饮管理系统\bin\Debug”中创建一个"DatabaseConnectString.txt"
            //把连接字符串存在这个txt中 
            string path = @"DatabaseConnectString.txt";
            if (File.Exists(path))
            {
                string connectionString = File.ReadAllText(path,Encoding.Default);
                //string connectionString = "Data Source=SAUSAGE-PC;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=sa;Password=tongji";
                conn = new SqlConnection(connectionString);
                conn.Open();
            }
        }

        public void Close()
        {
            conn.Close();
        }

        public SqlDataReader GetDataReader(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader dataReader = cmd.ExecuteReader();
            return dataReader;
        }

        public object ExecuteScaler(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            return cmd.ExecuteScalar();
        }

        public void ExecuteQuery(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
        }

        //public void UpdatePhoto(string tableName, string columnName, Byte[]imageByte, string id)
        //{
        //    SqlCommand cmd = new SqlCommand();
        //    cmd.Connection = conn;
        //    cmd.CommandText = "update "+tableName+" set "+columnName+" = @imgfile where id = " + id;
        //    SqlParameter par = new SqlParameter("@imgfile", SqlDbType.Image);
        //    par.Value = imageByte;
        //    cmd.Parameters.Add(par);
        //    int t = (int)(cmd.ExecuteNonQuery());
        //}

        public void ExecuteQuery(string sql, SqlParameter parameter)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            cmd.Parameters.Add(parameter);
            cmd.ExecuteNonQuery();
        }

        public static BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
        {
            BitmapImage bmp = null;

            try
            {
                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byteArray);
                bmp.EndInit();
            }
            catch
            {
                bmp = null;
            }

            return bmp;
        }
    }
}
